package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param param
     * @return
     */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){
        try {
            //获取到手机号
            String phone = param.get("phone");
            //获取验证码
            String code = param.get("verificationCode");
            //调用service层的login方法 ,传入手机号和验证码，返回一个data
            String data = this.userService.login(phone, code);
            //判断如果不为空那么就表示登录成功了
            if(StringUtils.isNotEmpty(data)){
                //登录成功，定义一个map来存储对象初始值设置为2
                Map<String, Object> result = new HashMap<>(2);
                //拆分返回过来的data，获取到token和isnew
                String[] ss = StringUtils.split(data, '|');
                result.put("token", ss[0]);
                result.put("isNew", Boolean.valueOf(ss[1]));
                //返回成功信息
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }

}
